package com.globallogic.model.dao;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import com.globallogic.model.entity.EntityInterface;

@Stateless
public class CommonDaoImpl<T extends EntityInterface<T1>, T1> implements
		CommonDao<T, T1> {

	public T getById(int id) {
		return em.find(clazz, id);
	}

	public T insert(T t) {
		em.persist(t);
		return t;
	}

	@Override
	public boolean delete(int id) {
		T entityToRemove = getById(id);
		if (null != entityToRemove) {
			em.remove(getById(id));
			return true;
		} else {
			return false;
		}

	}

	public List<T> getAll() {

		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<T> cq = cb.createQuery(clazz);
		Root<T> item = cq.from(clazz);
		cq.select(item);
		TypedQuery<T> q = em.createQuery(cq);
		List<T> allItems = q.getResultList();
		return allItems;

	}

	@PersistenceContext(unitName = "DailyPlanner")
	protected EntityManager em;

	@Override
	public <T2 extends EntityInterface<T1>> T2 update(T2 t) {
		
		T entity = em.find(clazz, t.getPrimaryKey());
		
		if (null == entity) {
			System.out.println("###!!!entity for class:" + clazz
					+ "and primary key: " + t.getPrimaryKey() + "not found");
			return null;
		} else {
			System.out.println("###Before merge: " + entity);
			em.merge(t);
			entity = em.find(clazz, t.getPrimaryKey());
			System.out.println("###After  merge: " + entity);
			
//			return entity;		
//			return em.find(clazz, t.getPrimaryKey());
			return t;
		}

	}

	protected Class<T> clazz;

}
